<template>
  <div class="user-profile">
    <div class="profile-header">
      <h1>个人中心</h1>
    </div>

    <div class="profile-content">
      <!-- 左侧导航 -->
      <div class="profile-sidebar">
        <!-- 动物头像 -->
        <div class="avatar-container">
          <PixelAvatar size="120" :userId="(userStore?.userInfo?.userId || userStore?.userInfo?.id || 'default')" />
        </div>

        <nav class="profile-nav">
          <ul>
            <li :class="{ active: activeTab === 'profile' }" @click="activeTab = 'profile'">
              <i class="fa fa-user"></i>
              个人资料
            </li>
            <li :class="{ active: activeTab === 'reservations' }" @click="activeTab = 'reservations'">
              <i class="fa fa-calendar"></i>
              个人预约
            </li>
            <li :class="{ active: activeTab === 'messages' }" @click="activeTab = 'messages'">
              <i class="fa fa-bell"></i>
              个人消息
              <span v-if="unreadCount > 0" class="badge">{{ unreadCount }}</span>
            </li>
          </ul>

          <button class="logout-btn" @click="handleLogout">
            <i class="fa fa-sign-out"></i>
            退出登录
          </button>
        </nav>
      </div>

      <!-- 右侧内容区域 -->
      <div class="profile-main">
        <!-- 个人资料 -->
        <div v-if="activeTab === 'profile'" class="tab-content profile-tab">
          <h2>个人资料</h2>

          <!-- 基本信息展示区域 -->
          <div class="info-display" v-if="!isEditing">
            <div class="info-card">
              <div class="info-item">
                <label>昵称</label>
                <span>{{ userData.nickname || '未设置' }}</span>
              </div>
              <div class="info-item">
                <label>手机号</label>
                <span>{{ userData.phone || '未设置' }}</span>
              </div>
              <div class="info-item">
                <label>密码</label>
                <span>••••••••</span>
              </div>
              <div class="info-item">
                <label>积分</label>
                <span class="points">{{ userData.points || 0 }}</span>
              </div>
              <div class="info-item">
                <label>会员剩余天数</label>
                <span class="days-remaining">{{ userData.remainingDays || 0 }} 天</span>
              </div>
            </div>
          </div>

          <!-- 编辑表单 -->
          <div class="edit-form" v-else>
            <form @submit.prevent="updateProfile">
              <div class="form-group">
                <label for="nickname">昵称</label>
                <input
                    type="text"
                    id="nickname"
                    v-model="editData.nickname"
                    placeholder="请输入昵称"
                    class="form-input"
                >
              </div>

              <div class="form-group">
                <label for="phone">手机号</label>
                <input
                    type="tel"
                    id="phone"
                    v-model="editData.phone"
                    placeholder="请输入手机号"
                    class="form-input"
                    pattern="[0-9]{11}"
                >
              </div>

              <div class="form-group">
                <label for="oldPassword">原密码（修改密码时必填）</label>
                <input
                    type="password"
                    id="oldPassword"
                    v-model="editData.oldPassword"
                    placeholder="修改密码时请输入原密码"
                    class="form-input"
                >
              </div>

              <div class="form-group">
                <label for="password">新密码（可选）</label>
                <input
                    type="password"
                    id="password"
                    v-model="editData.newPassword"
                    placeholder="请输入新密码，不修改请留空"
                    class="form-input"
                >
                <small v-if="editData.newPassword" class="form-help">密码长度至少6位</small>
              </div>

              <div class="form-group">
                <label for="confirmPassword">确认新密码</label>
                <input
                    type="password"
                    id="confirmPassword"
                    v-model="editData.confirmPassword"
                    placeholder="请确认新密码"
                    class="form-input"
                >
              </div>

              <div class="form-actions">
                <button type="button" class="btn-secondary" @click="cancelEditing">取消</button>
                <button type="submit" class="btn-primary">保存修改</button>
              </div>
            </form>
          </div>
        </div>

        <!-- 个人预约 -->
        <div v-if="activeTab === 'reservations'" class="tab-content reservations-tab">
          <h2>我的预约</h2>

          <div v-if="loadingReservations" class="loading-container">
            <div class="spinner"></div>
            <p>加载中...</p>
          </div>

          <div v-else-if="reservations.length === 0" class="empty-state">
            <i class="fa fa-calendar-times-o"></i>
            <p>暂无预约记录</p>
          </div>

          <div v-else class="reservations-list">
            <div v-for="reservation in reservations" :key="reservation.id" class="reservation-card">
              <div class="reservation-header">
                <h3>{{ reservation.courseName }}</h3>
                <span class="reservation-status" :class="reservation.status">{{ getStatusText(reservation.status) }}</span>
              </div>
              
              <!-- 取消预约按钮 - 仅在预约中和已确认状态显示 -->
              <div v-if="reservation.status === 'pending' || reservation.status === 'confirmed'" class="reservation-actions">
                <button class="btn-cancel" @click="showCancelModal(reservation)">
                  <i class="fa fa-times-circle"></i>
                  取消预约
                </button>
              </div>

              <div class="reservation-content">
                <div class="reservation-section">
                  <h4>课程信息</h4>
                  <div class="info-grid">
                    <div class="info-item border-bottom-item">
                      <i class="fa fa-clock-o"></i>
                      <span>课程时间：</span>
                      <span>{{ formatDateTimeRange(reservation.courseStartTime, reservation.courseEndTime) }}</span>
                    </div>
                    <div class="info-item border-bottom-item">
                      <i class="fa fa-sticky-note"></i>
                      <span>预约备注：</span>
                      <span class="notes-text">{{ reservation.notes || '无' }}</span>
                    </div>
                    <div class="info-item border-bottom-item">
                      <i class="fa fa-calendar-plus-o"></i>
                      <span>预约创建时间：</span>
                      <span>{{ formatDateTime(reservation.rcreatedAt) }}</span>
                    </div>
                    <div class="info-item border-bottom-item">
                      <i class="fa fa-calendar-check-o"></i>
                      <span>预约修改时间：</span>
                      <span>{{ formatDateTime(reservation.rupdatedAt) }}</span>
                    </div>
                  </div>
                </div>

                <div class="reservation-section">
                  <h4>教练信息</h4>
                  <div class="info-grid">
                    <div class="info-item border-bottom-item">
                      <i class="fa fa-user"></i>
                      <span>教练姓名：</span>
                      <span>{{ reservation.coachName }}</span>
                    </div>
                    <div class="info-item border-bottom-item">
                      <i class="fa fa-phone"></i>
                      <span>教练电话：</span>
                      <span class="coach-phone">{{ reservation.coachPhone || '未设置' }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 个人消息 -->
        <div v-if="activeTab === 'messages'" class="tab-content messages-tab">
          <h2>我的消息</h2>

          <!-- 消息操作按钮 -->
          <div class="message-actions" v-if="messages.length > 0">
            <button class="btn-secondary" @click="markAllAsRead" :disabled="unreadCount === 0">
              <i class="fa fa-check-circle"></i>
              全部标记为已读
            </button>
            <button class="btn-secondary" @click="deleteReadMessages" :disabled="!hasReadMessages">
              <i class="fa fa-trash"></i>
              删除已读消息
            </button>
          </div>

          <div v-if="loadingMessages" class="loading-container">
            <div class="spinner"></div>
            <p>加载中...</p>
          </div>

          <div v-else-if="messages.length === 0" class="empty-state">
            <i class="fa fa-envelope-o"></i>
            <p>暂无消息</p>
          </div>

          <div v-else class="messages-list">
            <div
                v-for="message in messages"
                :key="message.id"
                class="message-item"
                :class="{ unread: !message.read }"
                @click="markAsRead(message)"
            >
              <div class="message-header">
                <h4>{{ message.title }}</h4>
                <div class="message-meta">
                  <span class="message-type" :class="getMessageTypeClass(message.type)">{{ getMessageTypeText(message.type) }}</span>
                  <span class="message-time">{{ formatTime(message.createdAt) }}</span>
                </div>
              </div>
              <p class="message-content">{{ message.content }}</p>
              <div class="message-footer" v-if="message.relatedId">
                <span class="related-info">及时查看消息能够更好的获取到优质的课程消息噢！</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 取消预约模态框 -->
  <div class="modal" v-if="showCancelReservationModal">
    <div class="modal-overlay" @click="closeCancelModal"></div>
    <div class="modal-content">
      <div class="modal-header">
        <h3>取消预约</h3>
        <button class="close-btn" @click="closeCancelModal">&times;</button>
      </div>
      <div class="modal-body">
        <p>您确定要取消课程「{{ currentReservation?.courseName }}」的预约吗？</p>
        <div class="form-group">
          <label for="cancelReason">请输入取消原因：</label>
          <textarea 
            id="cancelReason" 
            v-model="cancelReason" 
            rows="3" 
            placeholder="请输入取消预约的原因" 
            class="form-input"
          ></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn-secondary" @click="closeCancelModal">返回</button>
        <button class="btn-cancel" @click="cancelReservation">确认取消</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 取消预约按钮样式 */
.reservation-actions {
  margin-top: 15px;
  text-align: right;
}

.btn-cancel {
  background-color: #ff4d4f;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.btn-cancel:hover {
  background-color: #ff7875;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: relative;
  background-color: white;
  border-radius: 8px;
  padding: 0;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1001;
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s;
}

.close-btn:hover {
  background-color: #f5f5f5;
  color: #333;
}

.modal-body {
  padding: 24px;
}

.modal-body p {
  margin-bottom: 16px;
  color: #333;
}

.modal-body .form-group {
  margin-bottom: 0;
}

.modal-body label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.modal-body textarea {
  width: 100%;
  resize: vertical;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.btn-secondary {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #d9d9d9;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-secondary:hover {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}
</style>

<script>
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/auth'
import request from '@/utils/request'
import PixelAvatar from '@/components/common/PixelAvatar.vue'

export default {
  name: 'UserProfile',
  components: {
    PixelAvatar
  },
  setup() {
    const router = useRouter()
    const userStore = useUserStore()

    // 状态管理
    const activeTab = ref('profile')
    const loadingReservations = ref(false)
    const loadingMessages = ref(false)
    const isEditing = ref(false)
    const loading = ref(false)

    // 用户数据
    const userData = ref({
      nickname: '',
      phone: '',
      points: 0,
      remainingDays: 0
    })

    // 编辑数据
    const editData = ref({
      nickname: '',
      phone: '',
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    // 预约数据
    const reservations = ref([])
    
    // 取消预约相关数据
    const showCancelReservationModal = ref(false)
    const currentReservation = ref(null)
    const cancelReason = ref('')

    // 消息数据
    const messages = ref([])

    // 未读消息数
    const unreadCount = ref(0)

    // 计算属性：是否有已读消息
    const hasReadMessages = computed(() => {
      return messages.value.some(msg => msg.read)
    })

    // 获取用户信息
    const fetchUserInfo = async () => {
      loading.value = true;
      try {
        console.log('开始获取用户信息');

        // 从localStorage获取userId
        const userId = localStorage.getItem('userId');
        console.log('从localStorage获取的userId:', userId);

        if (!userId) {
          console.error('无法从首页获取userId');
          alert('请先登录');
          router.push('/');
          return;
        }

        // 调用真实后端API
        const response = await request.get(`/api/users/${userId}`);

        // 处理嵌套的data对象
        const resultData = response.data || {};
        const userInfo = resultData.data || {};
        console.log('从后端API获取的原始用户信息:', userInfo);

        // 处理重复字段映射，确保数据一致性
        userData.value = {
          ...userInfo,
          nickname: userInfo.unickname || userInfo.nickname || userInfo.UNickname || userInfo.uNickname || '健身用户',
          phone: userInfo.mobile || userInfo.phone || userInfo.UMobile || userInfo.uMobile || '',
          points: userInfo.points || userInfo.u_points || userInfo.UPoints || userInfo.uPoints || 0,
          remainingDays: userInfo.remainingDays || userInfo.u_rt || userInfo.URt || userInfo.uRt || 0,
          userId: userInfo.userId || userId,
          // 存储完整的用户信息，方便后续使用
          ...userInfo
        };

        console.log('映射后的用户数据:', userData.value);

        // 更新到userStore，保持状态同步
        userStore.setUserInfo(userData.value);

        console.log('用户信息获取成功');
      } catch (error) {
        console.error('获取用户信息失败:', error);
        alert('获取用户信息失败，请稍后重试');
      } finally {
        loading.value = false;
      }
    }

    // 开始编辑
    const startEditing = () => {
      editData.value = {
        nickname: userData.value.nickname || '',
        phone: userData.value.phone || '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      isEditing.value = true
    }

    // 取消编辑
    const cancelEditing = () => {
      isEditing.value = false
      editData.value = {
        nickname: '',
        phone: '',
        newPassword: '',
        confirmPassword: ''
      }
    }

    // 更新个人信息方法
    const updateProfile = async () => {
      // 表单验证
      if (!editData.value.nickname.trim()) {
        alert('昵称不能为空');
        return;
      }

      if (editData.value.phone && !/^1[3-9]\d{9}$/.test(editData.value.phone)) {
        alert('请输入正确的手机号');
        return;
      }

      // 密码验证
      if (editData.value.newPassword) {
        if (!editData.value.oldPassword) {
          alert('修改密码时必须输入原密码');
          return;
        }

        if (editData.value.newPassword.length < 6) {
          alert('新密码长度至少为6位');
          return;
        }

        if (editData.value.newPassword !== editData.value.confirmPassword) {
          alert('两次输入的新密码不一致');
          return;
        }
      }

      loading.value = true;
      try {
        const userId = localStorage.getItem('userId');

        if (!userId) {
          alert('无法获取用户ID');
          return;
        }

        // 记录哪些字段被修改了，用于成功提示
        const changedFields = [];
        if (editData.value.nickname !== userData.value.nickname) {
          changedFields.push('昵称');
        }
        if (editData.value.phone !== userData.value.phone) {
          changedFields.push('手机号');
        }
        if (editData.value.newPassword) {
          changedFields.push('密码');
        }

        // 构建更新数据，使用正确的字段名
        const updateData = {
          nickname: editData.value.nickname,
          mobile: editData.value.phone, // 确保使用正确的字段名
        };

        // 只有当用户输入了新密码时，才传递原密码和新密码进行密码修改
        // 确保前端和后端的逻辑一致：只有想修改密码时才需要验证原密码
        if (editData.value.newPassword && editData.value.newPassword.trim()) {
          // 确保原密码不为空
          if (editData.value.oldPassword && editData.value.oldPassword.trim()) {
            updateData.oldPassword = editData.value.oldPassword.trim();
            updateData.newPassword = editData.value.newPassword.trim();
          } else {
            // 这里是额外保障，理论上前面的验证已经处理了这种情况
            alert('修改密码时必须输入原密码');
            loading.value = false;
            return;
          }
        }

        // 调用真实后端API
        const response = await request.put(`/api/users/${userId}`, updateData);

        // 处理后端返回的ResponseEntity<Result<Boolean>>格式
        const result = response.data; // 获取Result对象

        // 根据Result对象判断成功或失败
        if (result && result.code === 200 || result && result.success) {
          isEditing.value = false;
          // 根据修改的字段显示对应的成功提示
          if (changedFields.length > 0) {
            // 检查是否修改了密码
            if (changedFields.includes('密码')) {
              alert('密码修改成功，请重新登录');
              // 延迟执行退出登录，让用户看到提示
              setTimeout(() => {
                // 调用退出登录方法
                userStore.logout();
                // 跳转到登录页面或打开登录模态框
                router.push('/');
              }, 1000);
            } else {
              // 更新成功后，重新获取最新的用户信息
              await fetchUserInfo();
              alert(`${changedFields.join('、')}修改成功`);
            }
          } else {
            // 更新成功后，重新获取最新的用户信息
            await fetchUserInfo();
            alert(result.msg || '个人信息更新成功');
          }
        } else {
          // 优化错误提示，特别是原密码错误的情况
          const errorMsg = String(result?.msg || '更新失败');
          console.log('后端返回的错误消息:', errorMsg);
          // 更准确地识别原密码错误
          if (errorMsg.includes('密码') && (errorMsg.includes('错误') || errorMsg.includes('不正确') || errorMsg.includes('无效'))) {
            alert('原密码输入错误');
          } else if (errorMsg.includes('原密码')) {
            alert('原密码输入错误');
          } else {
            alert(errorMsg);
          }
        }
      } catch (error) {
        console.error('更新个人信息失败:', error);
        // 更健壮地处理错误响应格式
        let errorMsg = '更新失败，请稍后重试';

        // 尝试从不同位置获取错误消息
        if (error.response?.data?.msg) {
          errorMsg = error.response.data.msg;
        } else if (error.response?.data) {
          errorMsg = typeof error.response.data === 'string' ? error.response.data : JSON.stringify(error.response.data);
        } else if (error.message) {
          errorMsg = error.message;
        }

        console.log('捕获的错误消息:', errorMsg);

        // 更准确地识别原密码错误
        const msgStr = String(errorMsg).toLowerCase();
        if (msgStr.includes('密码') && (msgStr.includes('错误') || msgStr.includes('不正确') || msgStr.includes('无效'))) {
          alert('原密码输入错误');
        } else if (msgStr.includes('原密码')) {
          alert('原密码输入错误');
        } else {
          alert(errorMsg);
        }
      } finally {
        loading.value = false;
      }
    }

    // 获取用户消息
    const fetchUserMessages = async () => {
      loadingMessages.value = true;
      try {
        const userId = userStore.userInfo?.u_id || userStore.userInfo?.userId || userStore.userInfo?.id || localStorage.getItem('userId');

        if (!userId) {
          console.error('无法获取用户ID');
          return;
        }

        console.log('开始获取用户消息，用户ID:', userId);

        // 调用后端API获取用户消息
        const response = await request.get(`/api/user-messages/user/${userId}`);
        console.log('消息API返回的数据:', response.data);

        // 处理后端返回的数据格式
        const resultData = response.data || {};
        const messageList = resultData.data || [];

        // 映射消息字段，将后端字段转换为前端期望的格式
        messages.value = messageList.map(msg => ({
          id: msg.id,
          userId: msg.userId,
          title: msg.title || '系统通知',
          content: msg.content || '',
          type: msg.type || 'SYSTEM_NOTICE',
          read: msg.isRead === 1, // 将数字转换为布尔值
          relatedId: msg.relatedId,
          createdAt: msg.createdAt
        }));

        console.log('处理后的消息数据:', messages.value);

        // 获取未读消息数量
        await fetchUnreadCount();

      } catch (error) {
        console.error('获取用户消息失败:', error);
        // 如果获取失败，显示空状态
        messages.value = [];
        unreadCount.value = 0;
        alert('获取消息失败，请稍后重试');
      } finally {
        loadingMessages.value = false;
      }
    }

    // 获取未读消息数量
    const fetchUnreadCount = async () => {
      try {
        const userId = userStore.userInfo?.u_id || userStore.userInfo?.userId || userStore.userInfo?.id || localStorage.getItem('userId');

        if (!userId) {
          console.error('无法获取用户ID');
          return;
        }

        const response = await request.get(`/api/user-messages/user/${userId}/unread-count`);
        console.log('未读消息数量API返回:', response.data);

        const resultData = response.data || {};
        unreadCount.value = resultData.data || 0;

      } catch (error) {
        console.error('获取未读消息数量失败:', error);
        // 如果获取失败，从前端数据计算未读数量
        unreadCount.value = messages.value.filter(msg => !msg.read).length;
      }
    }

    // 标记消息为已读
    const markAsRead = async (message) => {
      // 如果消息已经是已读状态，直接返回
      if (message.read) return;

      try {
        console.log('标记消息为已读，消息ID:', message.id);

        const response = await request.put(`/api/user-messages/${message.id}/read`);
        console.log('标记已读API返回:', response.data);

        const resultData = response.data || {};
        if (resultData.code === 200 || resultData.success) {
          // 更新本地消息状态
          message.read = true;
          // 更新未读消息数量
          unreadCount.value = Math.max(0, unreadCount.value - 1);
          console.log('消息标记为已读成功');
        } else {
          alert(resultData.msg || '标记消息为已读失败');
        }
      } catch (error) {
        console.error('标记消息为已读失败:', error);
        alert('标记消息为已读失败，请稍后重试');
      }
    }

    // 标记所有消息为已读
    const markAllAsRead = async () => {
      if (unreadCount.value === 0) return;

      try {
        const userId = userStore.userInfo?.u_id || userStore.userInfo?.userId || userStore.userInfo?.id || localStorage.getItem('userId');

        if (!userId) {
          alert('无法获取用户ID');
          return;
        }

        console.log('标记所有消息为已读，用户ID:', userId);

        const response = await request.put(`/api/user-messages/user/${userId}/read-all`);
        console.log('标记所有已读API返回:', response.data);

        const resultData = response.data || {};
        if (resultData.code === 200 || resultData.success) {
          // 更新所有消息为已读状态
          messages.value.forEach(msg => {
            msg.read = true;
          });
          // 重置未读消息数量
          unreadCount.value = 0;
          alert('所有消息已标记为已读');
        } else {
          alert(resultData.msg || '标记所有消息为已读失败');
        }
      } catch (error) {
        console.error('标记所有消息为已读失败:', error);
        alert('标记所有消息为已读失败，请稍后重试');
      }
    }

    // 删除已读消息
    const deleteReadMessages = async () => {
      if (!hasReadMessages.value) return;

      if (!confirm('确定要删除所有已读消息吗？此操作不可恢复。')) {
        return;
      }

      try {
        const userId = userStore.userInfo?.u_id || userStore.userInfo?.userId || userStore.userInfo?.id || localStorage.getItem('userId');

        if (!userId) {
          alert('无法获取用户ID');
          return;
        }

        console.log('删除已读消息，用户ID:', userId);

        const response = await request.delete(`/api/user-messages/user/${userId}/read`);
        console.log('删除已读消息API返回:', response.data);

        const resultData = response.data || {};
        if (resultData.code === 200 || resultData.success) {
          // 从本地消息列表中移除已读消息
          messages.value = messages.value.filter(msg => !msg.read);
          alert('已读消息删除成功');
        } else {
          alert(resultData.msg || '删除已读消息失败');
        }
      } catch (error) {
        console.error('删除已读消息失败:', error);
        alert('删除已读消息失败，请稍后重试');
      }
    }

    // 获取消息类型文本
    const getMessageTypeText = (type) => {
      const typeMap = {
        'SYSTEM_NOTICE': '系统通知',
        'COURSE_BOOKING': '课程预约',
        'COURSE_CANCEL': '预约取消',
        'ACCOUNT_NOTICE': '账户通知'
      };
      return typeMap[type] || '系统消息';
    }

    // 获取消息类型样式类
    const getMessageTypeClass = (type) => {
      const classMap = {
        'SYSTEM_NOTICE': 'system',
        'COURSE_BOOKING': 'booking',
        'COURSE_CANCEL': 'cancel',
        'ACCOUNT_NOTICE': 'account'
      };
      return classMap[type] || 'system';
    }

    // 获取用户预约记录
    const fetchUserReservations = async () => {
      // 尝试从userStore获取用户ID，支持多种可能的字段名
      // 添加默认值1用于测试
      const userId = userStore.userInfo?.u_id || userStore.userInfo?.userId || userStore.userInfo?.id || localStorage.getItem('userId') || '1';

      console.log('使用的用户ID:', userId);

      loadingReservations.value = true;
      try {
        console.log('开始获取预约记录，用户ID:', userId);
        const { data } = await request.get(`/api/reservations/user/${userId}/dto`);

        console.log('API返回的数据:', data);

        // 后端已返回DTO格式，需要将后端字段映射到前端期望的字段名
        reservations.value = data.map(item => ({
          ...item,
          // 映射字段：后端返回的字段 -> 前端期望的字段
          coachPhone: item.coachPhone || item.phone,  // 教练电话：确保使用正确的字段名
          status: mapStatus(item.status || item.rstatus),  // 预约状态：优先使用status，然后使用rstatus
          rcreatedAt: item.createdAt || item.rcreatedAt,  // 预约创建时间：现在后端返回createdAt
          rupdatedAt: item.updatedAt || item.rupdatedAt,  // 预约修改时间：现在后端返回updatedAt
          // 确保课程时间字段名称正确
          courseStartTime: item.courseStartTime || item.c_time,
          courseEndTime: item.courseEndTime || item.c_endTime,
        }));

        console.log('处理后的预约数据:', reservations.value);
      } catch (error) {
        console.error('获取预约记录失败:', error);
        // 如果新接口失败，尝试回退到旧接口
        try {
          console.log('尝试使用旧接口获取预约记录');
          const { data: oldData } = await request.get(`/api/reservations/user/${userId}`);
          console.log('旧接口返回的数据:', oldData);

          reservations.value = oldData.map(item => ({
            id: item.r_id || item.id,
            courseName: item.c_name || item.courseName || '未知课程',
            coachName: item.coach_name || item.coachName || '未知教练',
            coachPhone: item.phone || item.coachPhone || '未设置',  // 教练电话
            courseStartTime: item.c_time || item.reservationTime || '',
            courseEndTime: item.c_time ? new Date(new Date(item.c_time).getTime() + (item.c_duration || 60) * 60000) : item.endTime || '',
            notes: item.r_notes || '',
            status: mapStatus(item.r_status || item.status),
            rcreatedAt: item.r_created_at || item.createdAt || new Date(),  // 预约创建时间
            rupdatedAt: item.r_updated_at || item.updatedAt || new Date()  // 预约修改时间
          }));

          console.log('旧接口处理后的预约数据:', reservations.value);
        } catch (fallbackError) {
          console.error('回退到旧接口也失败:', fallbackError);
          // 添加用户友好的错误提示
          alert('获取预约记录失败，请刷新页面重试');
        }
      } finally {
        loadingReservations.value = false;
      }
    }

    // 格式化开始时间
    const formatStartTime = (dateTime) => {
      const date = new Date(dateTime);
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      });
    }

    // 格式化结束时间（基于开始时间和课程时长）
    const formatEndTime = (startTime, durationMinutes) => {
      const startDate = new Date(startTime);
      const endDate = new Date(startDate.getTime() + durationMinutes * 60 * 1000);
      return endDate.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      });
    }

    // 状态映射函数 - 支持数字状态、英文状态和中文状态
    const mapStatus = (status) => {
      // 处理数字状态
      if (typeof status === 'number') {
        switch(status) {
          case 0: return 'pending';
          case 1: return 'confirmed';
          case 2: return 'completed';
          case 3: return 'canceled';
          default: return 'pending';
        }
      }

      // 处理中文状态
      if (typeof status === 'string') {
        // 中文状态映射
        const chineseStatusMap = {
          '待确认': 'pending',
          '已确认': 'confirmed',
          '已完成': 'completed',
          '已取消': 'canceled'
        };

        // 如果是中文状态，返回对应的英文状态
        if (chineseStatusMap[status]) {
          return chineseStatusMap[status];
        }

        // 如果是英文状态，确保它是我们期望的值
        const validStatuses = ['pending', 'confirmed', 'completed', 'canceled'];
        if (validStatuses.includes(status)) {
          return status;
        }
      }

      // 默认返回待确认状态
      return 'pending';
    };

    // 状态文本转换函数
    const getStatusText = (status) => {
      // 处理null或undefined的情况
      if (!status) return '待确认';

      const statusMap = {
        pending: '待确认',
        confirmed: '已确认',
        completed: '已完成',
        canceled: '已取消'
      };
      return statusMap[status] || '未知状态';
    };

    // 监听标签页切换，当切换到预约标签页时获取预约记录
    watch(() => activeTab.value, (newTab) => {
      if (newTab === 'reservations') {
        fetchUserReservations();
      } else if (newTab === 'messages') {
        fetchUserMessages();
      }
    })

    // 日期格式化函数
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    // 日期时间格式化函数
    const formatDateTime = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    };

    // 显示取消预约模态框
    const showCancelModal = (reservation) => {
      currentReservation.value = reservation;
      showCancelReservationModal.value = true;
      cancelReason.value = '';
    }
    
    // 关闭取消预约模态框
    const closeCancelModal = () => {
      showCancelReservationModal.value = false;
      currentReservation.value = null;
      cancelReason.value = '';
    }
    
    // 执行取消预约
    const cancelReservation = async () => {
      if (!currentReservation.value || !cancelReason.value.trim()) {
        alert('请输入取消原因');
        return;
      }
      
      try {
        const reservationId = currentReservation.value.id;
        const reason = cancelReason.value.trim();
        
        console.log('取消预约，预约ID:', reservationId, '取消原因:', reason);
        
        // 修改为使用查询参数传递取消原因，以匹配后端接口要求
        const response = await request.put(`/api/reservations/${reservationId}/cancel?reason=${encodeURIComponent(reason)}`);
        
        console.log('取消预约API返回:', response.data);
        
        // 由于后端直接返回字符串，这里调整响应处理逻辑
        if (response.data === '取消预约成功') {
          // 更新本地预约状态
          const index = reservations.value.findIndex(r => r.id === reservationId);
          if (index !== -1) {
            reservations.value[index].status = 'canceled';
          }
          
          alert('预约取消成功');
          closeCancelModal();
        } else {
          alert(response.data || '取消预约失败');
        }
      } catch (error) {
        console.error('取消预约失败:', error);
        // 从错误响应中提取具体错误信息
        if (error.response && error.response.data) {
          alert('取消预约失败: ' + error.response.data);
        } else {
          alert('取消预约失败，请稍后重试');
        }
      }
    }
    
    // 日期时间范围格式化函数
    const formatDateTimeRange = (startTime, endTime) => {
      if (!startTime) return '';
      const start = new Date(startTime);
      const end = endTime ? new Date(endTime) : null;

      const date = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')}`;
      const startTimeStr = `${String(start.getHours()).padStart(2, '0')}:${String(start.getMinutes()).padStart(2, '0')}`;
      const endTimeStr = end ? `${String(end.getHours()).padStart(2, '0')}:${String(end.getMinutes()).padStart(2, '0')}` : '待定';

      return `${date} ${startTimeStr} - ${endTimeStr}`;
    }

    // 格式化时间
    const formatTime = (dateString) => {
      const date = new Date(dateString)
      const now = new Date()
      const diff = now - date

      if (diff < 3600000) {
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) {
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return date.toLocaleDateString('zh-CN')
      }
    }

    // 退出登录
    const handleLogout = () => {
      if (confirm('确定要退出登录吗？')) {
        userStore.logout()
        router.push('/')
      }
    }

    // 生命周期钩子 - 简化版本
    onMounted(() => {
      // 直接调用获取用户信息方法
      fetchUserInfo();

      // 如果默认是预约标签页，获取预约记录
      if (activeTab.value === 'reservations') {
        fetchUserReservations();
      } else if (activeTab.value === 'messages') {
        fetchUserMessages();
      }
    })

    // 返回数据和方法
    return {
      activeTab,
      userData,
      editData,
      isEditing,
      loading,
      reservations,
      messages,
      unreadCount,
      loadingReservations,
      loadingMessages,
      hasReadMessages,
      startEditing,
      cancelEditing,
      updateProfile,
      getStatusText,
      formatDate,
      formatTime,
      formatDateTime,
      formatDateTimeRange,
      formatStartTime,
      formatEndTime,
      mapStatus,
      fetchUserReservations,
      fetchUserMessages,
      markAsRead,
      markAllAsRead,
      deleteReadMessages,
      getMessageTypeText,
      getMessageTypeClass,
      handleLogout,
      // 取消预约相关
      showCancelReservationModal,
      currentReservation,
      cancelReason,
      showCancelModal,
      closeCancelModal,
      cancelReservation
    }
  }
}
</script>

<style scoped>
.user-profile {
  min-height: 100vh;
  background-color: #f7fafc;
  padding: 2rem 1rem;
}

.profile-header {
  text-align: center;
  margin-bottom: 2rem;
}

.profile-header h1 {
  color: #2d3748;
  font-size: 1.875rem;
  font-weight: 700;
}

.profile-content {
  display: grid;
  grid-template-columns: 1fr 3fr;
  gap: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

/* 侧边栏样式 */
.profile-sidebar {
  background-color: #ffffff;
  border-radius: 0.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  position: sticky;
  top: 2rem;
  height: fit-content;
}

.avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: 2rem;
}

.profile-nav ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.profile-nav li {
  display: flex;
  align-items: center;
  padding: 0.75rem 1rem;
  margin-bottom: 0.5rem;
  border-radius: 0.375rem;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
  color: #4a5568;
}

.profile-nav li:hover {
  background-color: #f7fafc;
}

.profile-nav li.active {
  background-color: #e6fffa;
  color: #2b6cb0;
  font-weight: 500;
  /* 确保没有任何类型的指示器 */
  border-left: none;
  border-right: none;
  border-top: none;
  border-bottom: none;
}

/* 确保没有通过伪元素添加的指示器 */
.profile-nav li.active::before,
.profile-nav li.active::after {
  display: none;
}

.profile-nav li i {
  margin-right: 0.75rem;
  font-size: 1.25rem;
  width: 2rem;
  height: 2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #edf2f7;
  color: #4a5568;
  border-radius: 0.5rem;
  transition: all 0.2s ease;
}

/* 活动状态的图标样式 */
.profile-nav li.active i {
  background-color: #3182ce;
  color: #ffffff;
}

/* 悬停状态的图标样式 */
.profile-nav li:hover i {
  background-color: #cbd5e0;
  color: #2d3748;
}

.badge {
  position: absolute;
  right: 0.75rem;
  top: 50%;
  transform: translateY(-50%);
  background-color: #f56565;
  color: white;
  font-size: 0.75rem;
  padding: 0.125rem 0.375rem;
  border-radius: 0.75rem;
  min-width: 1.5rem;
  text-align: center;
}

.logout-btn {
  width: 100%;
  padding: 0.75rem;
  margin-top: 2rem;
  background-color: #edf2f7;
  border: none;
  border-radius: 0.375rem;
  color: #4a5568;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logout-btn:hover {
  background-color: #e2e8f0;
}

.logout-btn i {
  margin-right: 0.5rem;
}

/* 主内容区域 */
.profile-main {
  background-color: #ffffff;
  border-radius: 0.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 2rem;
}

.tab-content h2 {
  color: #2d3748;
  font-size: 1.5rem;
  font-weight: 600;
  margin-bottom: 1.5rem;
}

/* 个人资料样式 */
.info-display .info-card {
  background-color: #f7fafc;
  border-radius: 0.5rem;
  padding: 1.5rem;
  margin-bottom: 1.5rem;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 0;
  border-bottom: 1px solid #e2e8f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item label {
  font-weight: 500;
  color: #4a5568;
}

.info-item span {
  color: #2d3748;
}

.info-item .points {
  color: #48bb78;
  font-weight: 600;
}

.info-item .days-remaining {
  color: #2b6cb0;
  font-weight: 600;
}

.edit-profile-btn {
  background-color: #3182ce;
  color: white;
  border: none;
  border-radius: 0.375rem;
  padding: 0.75rem 1.5rem;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.edit-profile-btn:hover {
  background-color: #2b6cb0;
}

/* 编辑表单样式 */
.edit-form form {
  max-width: 600px;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #4a5568;
}

.form-input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #e2e8f0;
  border-radius: 0.375rem;
  font-size: 1rem;
  transition: border-color 0.2s;
}

.form-input:focus {
  outline: none;
  border-color: #3182ce;
  box-shadow: 0 0 0 3px rgba(49, 130, 206, 0.1);
}

.form-help {
  display: block;
  margin-top: 0.25rem;
  font-size: 0.75rem;
  color: #718096;
}

.form-actions {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
}

.btn-primary {
  background-color: #3182ce;
  color: white;
  border: none;
  border-radius: 0.375rem;
  padding: 0.75rem 1.5rem;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-primary:hover {
  background-color: #2b6cb0;
}

.btn-secondary {
  background-color: #e2e8f0;
  color: #4a5568;
  border: none;
  border-radius: 0.375rem;
  padding: 0.75rem 1.5rem;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-secondary:hover {
  background-color: #cbd5e0;
}

/* 预约列表样式 */
.reservations-list {
  display: grid;
  gap: 1rem;
}

.reservation-card {
  background-color: #f7fafc;
  border-radius: 0.5rem;
  padding: 1rem;
  border-left: 4px solid #3182ce;
}

.reservation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.75rem;
}

.reservation-header h3 {
  color: #2d3748;
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0;
}

/* 预约卡片内容样式 - 优化为更紧凑、整齐的布局 */
.reservation-content {
  padding: 1rem;
  background: #ffffff;
  border-radius: 0.5rem;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
}

.reservation-section {
  margin-bottom: 0.75rem;
}

.reservation-section:last-child {
  margin-bottom: 0;
}

.reservation-section h4 {
  font-size: 0.95rem;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 0.75rem;
  padding-bottom: 0.375rem;
  border-bottom: 1px solid #e2e8f0;
}

/* 优化为两列网格布局，使数据更整齐 */
.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0.5rem 1rem;
}

/* 确保信息项对齐整齐 */
.info-item {
  display: flex;
  align-items: center;
  color: #2d3748;
  font-size: 1rem;
  margin-bottom: 1rem;
}

.info-item i {
  color: #3182ce;
  margin-right: 0.5rem;
  font-size: 1rem;
  width: 1.25rem;
  text-align: center;
  flex-shrink: 0;
  /* 确保没有背景或边框显示 */
  background: none;
  border: none;
}

/* 个人资料中的label样式 */
.info-item label {
  font-weight: 500;
  color: #4a5568;
  margin-right: 1rem;
  min-width: 80px;
  flex-shrink: 0;
}

/* 预约卡片中特定的info-item样式，使用更具体的选择器 */
.reservation-content .info-item {
  display: flex;
  align-items: flex-start;
  font-size: 0.875rem;
  margin-bottom: 0;
  min-height: 1.75rem;
}

.reservation-content .info-item span:first-of-type {
  font-weight: 500;
  color: #4a5568;
  margin-right: 0.5rem;
  min-width: 80px; /* 固定标签宽度，确保对齐 */
  flex-shrink: 0;
}

/* 预约卡片中特定的内容样式 */
.reservation-content .info-item span:last-child {
  flex: 1;
  word-break: break-word;
}

.notes-text {
  color: #2d3748;
  font-style: italic;
}

.coach-phone {
  color: #3182ce;
  font-weight: 500;
}

/* 底部有横线的信息项 - 使用更明显的样式确保用户能看到 */
.reservation-content .info-grid .info-item.border-bottom-item {
  padding-bottom: 0.75rem !important;
  border-bottom: 2px solid #a0aec0 !important; /* 使用更粗更深的灰色线条 */
  margin-bottom: 0.75rem !important;
  /* 增加间距以更好地显示横线 */
  width: 100% !important;
  display: flex !important;
}

/* 状态标签样式 */
.reservation-status {
  padding: 0.375rem 0.75rem;
  border-radius: 9999px;
  font-size: 0.875rem;
  font-weight: 500;
}

/* 确保状态类名与mapStatus函数返回的值完全匹配 */
.reservation-status.pending {
  background-color: #fffaf0;
  color: #c05621;
}

.reservation-status.confirmed {
  background-color: #e6fffa;
  color: #2b6cb0;
}

.reservation-status.completed {
  background-color: #f0fff4;
  color: #22543d;
}

.reservation-status.canceled {
  background-color: #fff5f5;
  color: #c53030;
}

/* 兼容可能的数字状态值 */
.reservation-status[class*="0"] {
  background-color: #fffaf0;
  color: #c05621;
}

.reservation-status[class*="1"] {
  background-color: #e6fffa;
  color: #2b6cb0;
}

.reservation-status[class*="2"] {
  background-color: #f0fff4;
  color: #22543d;
}

.reservation-status[class*="3"] {
  background-color: #fff5f5;
  color: #c53030;
}

.reservation-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;
}

.reservation-info .info-item {
  border: none;
  padding: 0;
  display: flex;
  align-items: center;
  margin-bottom: 0.5rem;
}

.reservation-info .info-item i {
  color: #718096;
  margin-right: 0.5rem;
}

/* 消息列表样式 */
.messages-list {
  display: grid;
  gap: 1rem;
}

.message-item {
  background-color: #f7fafc;
  border-radius: 0.5rem;
  padding: 1.25rem;
  cursor: pointer;
  transition: background-color 0.2s;
  border-left: 3px solid transparent;
}

.message-item:hover {
  background-color: #edf2f7;
}

.message-item.unread {
  background-color: #ebf8ff;
  border-left-color: #3182ce;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.5rem;
}

.message-header h4 {
  color: #2d3748;
  font-size: 1.125rem;
  font-weight: 600;
  margin: 0;
  flex: 1;
}

.message-meta {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.message-type {
  font-size: 0.75rem;
  padding: 0.25rem 0.5rem;
  border-radius: 0.25rem;
  font-weight: 500;
}

.message-type.system {
  background-color: #e2e8f0;
  color: #4a5568;
}

.message-type.booking {
  background-color: #c6f6d5;
  color: #22543d;
}

.message-type.cancel {
  background-color: #fed7d7;
  color: #c53030;
}

.message-type.account {
  background-color: #fefcbf;
  color: #744210;
}

.message-time {
  color: #718096;
  font-size: 0.875rem;
}

.message-content {
  color: #4a5568;
  margin: 0.5rem 0;
  line-height: 1.5;
}

.message-footer {
  margin-top: 0.5rem;
  padding-top: 0.5rem;
  border-top: 1px solid #e2e8f0;
}

.related-info {
  font-size: 0.75rem;
  color: #718096;
}

/* 消息操作按钮 */
.message-actions {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
  flex-wrap: wrap;
}

.message-actions .btn-secondary {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.875rem;
  padding: 0.5rem 1rem;
}

.message-actions .btn-secondary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 加载和空状态 */
.loading-container,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4rem 2rem;
  text-align: center;
  color: #718096;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #4ECDC4;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state i {
  font-size: 3rem;
  margin-bottom: 1rem;
  color: #cbd5e0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-content {
    grid-template-columns: 1fr;
  }

  .profile-sidebar {
    position: relative;
  }

  .profile-nav ul {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 0.5rem;
  }

  .profile-nav li {
    justify-content: center;
    padding: 0.75rem;
    font-size: 0.875rem;
  }

  .profile-nav li i {
    margin-right: 0.25rem;
    font-size: 1rem;
  }

  .badge {
    right: 0.5rem;
    font-size: 0.7rem;
    padding: 0.1rem 0.4rem;
  }

  .reservation-info {
    grid-template-columns: 1fr;
  }

  .message-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }

  .message-meta {
    width: 100%;
    justify-content: space-between;
  }

  .message-actions {
    flex-direction: column;
  }

  .message-actions .btn-secondary {
    justify-content: center;
  }
}
</style>